<template>
    <div class="component-fileupload">
        <el-upload
            :on-success="handleSuccess"
            :on-error="handleError"
            :class="uploadClass"
            :list-type="image?'picture-card':'text'"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :show-file-list="showList"
            :action="url"
            :data="uploadParams"
            :headers="headers"
            :disabled="!edit"
            :file-list="fileList"
            :limit="limit"
            :accept="image?accept:''"
            :before-upload="beforeUploadHandle"
            :on-change="handleChange"
        >
            <el-button v-if="!image" :size="buttonSize" :type="buttonType" :disabled="!edit"> {{ buttonName }}</el-button>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <slot></slot>
    </div>
</template>
<script>
import service from "@service";

import { getFileSizeName } from "@utils";
const getDownloadFile = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('xxxx');
        }, 200)
    })
};
export default {
    props:{
        uploadParamsHandle: {
            type: Function
        },
        serviceName: {
            type: String,
            required: true
        },
        imageFileList: {
            type: Array,
            default() {
                return [];
            }
        },
        accept:{
            type: String,
            default() {
                return "image/*";
            }
        },
        image:{
            type: Boolean,
            default() {
                return false;
            }
        },
        showList: {
            type: Boolean,
            default: false
        },
        buttonType:{
            type: String,
            default: "primary"
        },
        buttonSize:{
            type: String,
            default: "small"
        },
        buttonName: {
            type: String,
            default: "上传附件"
        },
        edit:{
            type: Boolean,
            default() {
                return false;
            }
        },
        limit: {
            type: Number,
            default: 1
        },
        fileSizeLimit: {
            type: Number,
            default: null
        },
    },
    data() {
        return {
            limited:false,
            uploadParams:{},
            headers:{},
            url: 'useless',
            uploadSuccess:"uploadSuccess",
            uploadError:"uploadError",
            uploadRemove:"uploadRemove",
            fileList: []
        };
    },
    computed: {
        uploadClass() {
            if(this.edit){
                if(this.fileList && this.fileList.length >= this.limit){
                    return "limit";
                }
                if(!this.permisision){
                    return "";
                }
                let name;
                if (typeof this.permisision === "string") {
                    name = this.permisision;
                }
                return "";
            }
            return "view";
        }
    },
    watch: {
        imageFileList:{
            immediate:true,
            handler(fileList){
                // this.loadImageFileList(fileList);
            }
        }
    },
    created(){

    },
    methods: {
        async loadImageFileList(fileList) {
            const files =[];
            for (let index = 0; index < fileList.length; index++) {
                let result = {};
                if(!fileList[index].url) {
                    result = await this.queryFileInfo(fileList[index].fileName,fileList[index].fileSeq || fileList[index].attachmentPath);
                }
                files.push({
                    ...fileList[index],
                    ...result,
                });
            }
            this.fileList = files;
        },
        async queryFileInfo(fileName,fileSeq) {
            const fileInfo = await getDownloadFile(fileSeq,{fileName}).catch(err => {
                throw err;
            });
            return {
                name:fileName,
                url: fileInfo["distUrl"]||""
            };
        },
        async handleSuccess(response, file, fileList) {
            this.$emit(this.uploadSuccess, file,fileList);
        },
        handleError(response, file, fileList) {
            if(this.image){
                this.limited = fileList.length >= this.limit;
            }
            const data={
                "response":response,
                "file":file,
                "fileList":fileList
            };
            this.$emit(this.uploadError, data);
        },
        handleRemove(file, fileList) {
            if(this.image){
                this.limited = fileList.length >= this.limit;
            }
            this.$emit(this.uploadRemove, file.data,fileList);
        },
        handlePreview(file) {
            const url = file.url || URL.createObjectURL(file.raw);
            this.$store.commit("global/OPEN_IMAGE", {
                src: url
            });
        },
        handleChange(file,fileList) {
            if(this.image){
                this.limited = fileList.length >= this.limit;
            }
        },
        beforeUploadHandle(file) {
            if(this.fileSizeLimit && file.size > this.fileSizeLimit) {
                this.$message.error(`文件大小不能大于${getFileSizeName(this.fileSizeLimit)}`);
                return false;
            }
            let params = {
                file: file
            }
            if(this.uploadParamsHandle) {
                params = this.uploadParamsHandle(params);
            }

            let formData = new FormData();

            if(params) {
                Object.keys(params).forEach(k => {
                    formData.append(k, params[k]);
                })
            }

            service(this.serviceName, {
                data: formData,
                timeout: 60000
            }).then(result => {
                if(result) {
                    this.$emit(this.uploadSuccess, result);
                }
            })
    
            return false;
        }
    },
};
</script>
<style lang="scss">
    .component-fileupload .view .el-upload{
        display: none;
    }
    .component-fileupload .limit .el-upload{
        display: none;
    }
</style>
